// ==UserScript==
// @name         批量删除主题
// @namespace    https://yk12510.gitee.io/static-resources/
// @version      1.0.1
// @description  try to take over the world!
// @author       You
// @match        http://www.ahedu.cn/SNS/index.php?app=research&mod=Index&act=index
// @grant        none
// @updateURL    https://yk12510.gitee.io/static-resources/002-script/deleteTopic.js
// ==/UserScript==

(function() {
  'use strict';

  // Your code here...
  const deleteTopicBtn = $('<a class="fr" href="javascript:void(0)">删除主题</a>')
  $('#right_header').prepend(deleteTopicBtn)
  deleteTopicBtn.click(() => {
    if (deleteTopicBtn.text() === '停止删除') {
      clearTimeout(timer)
      page = 1
      deleteTopicBtn.text('删除主题')
    } else {
      init()
    }
  })

  // 查询可删除的主题Id
  function queryIds () {
    const ids = []
    $('.topic_name a').each((index, item) => {
      let href = $(item).attr('href'),
        name = $(item).text()
      if (/\d+/.test(name)) {
        let id = (href.match(/id=\d+/) || [])[0]
        id && ids.push(id.split('=')[1])
        $(item).closest('dd').attr('rid', id.split('=')[1])
      }
    });
    return ids
  }

  // 删除主题
  function deleteTheme (rid) {
    $.post(U('research/Index/deleteResearch'), { rid: rid }, () => {
      deleteCount--
      $('dd[rid="' + rid + '"]').fadeOut()
      if (deleteCount < 1) {
        create.loadData(page);
        setTimeout(init, 500)
      }
    })
  }

  // 初始化
  let timer = null, queryCount = 0, deleteCount = 0, page = 1
  function init () {
    deleteTopicBtn.text('停止删除')
    // 检测主题存在
    let topicList = $('.topic_name a')
    if (topicList.length) {
      queryCount = 0
      deleteCount = 0
      const ids = queryIds()
      if (ids.length) {
        ids.forEach(id => {
          deleteCount++
          deleteTheme(id)
        })
      } else if ($('.present2').length && $('.present2').text() < (page + 2)) {
        create.loadData(++page);
        init();
      }
    } else {
      if (queryCount < (5 * 60 * 2)) setTimeout(init, 500) // 500毫秒后再查一次
    }
  }
})();
